package leetcode.Y2024M5D23;

import org.junit.Test;

import java.util.Arrays;
import java.util.Comparator;

public class S57 {
    public int[][] insert(int[][] intervals, int[] newInterval) {
        int[][] res = new int[intervals.length + 1][2];
        for (int i = 0; i < intervals.length; i++) {
            res[i][0] = intervals[i][0];
            res[i][1] = intervals[i][1];
        }
        res[intervals.length][0] = newInterval[0];
        res[intervals.length][1] = newInterval[1];
        Arrays.sort(res, Comparator.comparingInt(x -> x[0]));
        return merge(res);
    }

    public int[][] merge(int[][] intervals) {
        Arrays.sort(intervals, Comparator.comparingInt(x -> x[0]));
        int[][] res = new int[intervals.length][2];
        int index = 0;
        int indexR = 0;
        while (index < intervals.length) {
            int min = intervals[index][0];
            int max = intervals[index][1];
            // 条件需要优化
            while (index + 1 < intervals.length && max >= intervals[index + 1][0] && min <= intervals[index + 1][0]) {
                min = Math.min(min, intervals[index + 1][0]);
                max = Math.max(max, intervals[index + 1][1]);
                index++;
            }
            res[indexR] = new int[]{min, max};
            index++;
            indexR++;

        }
        int[][] r = new int[indexR][2];
        for (int i = 0; i < r.length; i++) {
            r[i][0] = res[i][0];
            r[i][1] = res[i][1];
        }
        return r;

    }

    @Test
    public void test() {
        int[][] intervals = {{1, 3}, {6, 9}};
        int[] newInterval = {2, 5};
        System.out.println(Arrays.deepToString(insert(intervals, newInterval)));
    }

    @Test
    public void test1() {
        int[][] intervals = {{1, 2}, {3, 5}, {6, 7}, {8, 10}, {12, 16}};
        int[] newInterval = {4, 8};
        System.out.println(Arrays.deepToString(insert(intervals, newInterval)));
    }


}
